package com.wehealth.three.lib_connect.device.usbdevice;

import android.hardware.usb.UsbDeviceConnection;
import android.os.Handler;
import android.os.Message;


import com.wehealth.three.lib_connect.device.usbdevice.data.ParseOriginEcgData;
import com.wehealth.three.lib_connect.device.usbdevice.port.UsbSerialPort;

import java.io.IOException;

/****
 * 二代机的usb传输的处理
 */
public class UsbSerialThread extends Thread {
    //串口开始采集数据
    private final int DRAW_ECG_WAVE = 1000;
    //usb数据传输失败
    private final int BT_CONNECT_FAILED = 997;
    //usb设备已连接
    private final int BT_CONNECTED = 996;
    //usb无法接收数据次数超过300次给出的错误提示
    private final int BT_CONNECT_DEVICE_ERROR = 899;
    //usb设备的读取超时时间
    private static final int READ_WAIT_MILLIS = 50;
    //每次从串口读取数据的数据量
    private static final int BUFSIZE = 9000;
    //是否正在接收数据
    private boolean isReceiveBTData = false;


    UsbDeviceConnection usbDConn;
    UsbSerialPort usPort;
    ParseOriginEcgData ecgParser24;
    Handler handler;

    int usbVersion;


    public UsbSerialThread(int usbVersion, UsbDeviceConnection usbConnection, UsbSerialPort usbSerialPort, Handler handle, ParseOriginEcgData.EcgDataGetListener ecgDataListener) {
        usbDConn = usbConnection;
        usPort = usbSerialPort;
        ecgParser24 = new ParseOriginEcgData(ecgDataListener);
        ecgParser24.ecgDataParserInit();
        handler = handle;
        this.usbVersion = usbVersion;

    }

    @Override
    public void run() {
        super.run();
        try {
            //提示usb已经连接
            handler.sendEmptyMessage(BT_CONNECTED);
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            usPort.open(usbDConn);
            //配置串口参数
            usPort.setParameters(921600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            usPort.setDTR(true);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //开始接受数据绘制
            handler.sendEmptyMessage(DRAW_ECG_WAVE);
            //设置数据解析使用的模式为心电数据传输
            ecgParser24.setModel();
            if (!isReceiveBTData){
                //通过串口发送开始命令
                usPort.write(ParseOriginEcgData.packEcgDeviceStart(), READ_WAIT_MILLIS);
                //是否在接受数据的状态为true
                isReceiveBTData = true;
            }
            //读取数据的缓存的大小
            byte[] data = new byte[BUFSIZE];
            // 无法正确接受数据的次数
            int unavailableCount = 0;

            //读取数据
            while (isReceiveBTData) {
                //串口读入数据
                int available = usPort.read(data, READ_WAIT_MILLIS);
                //创建一个缓存数组
                byte[] tmp = new byte[available];
                for (int i = 0; i < available; i++) {
                    tmp[i] = data[i];
                }
                //对采集到的原始数据进行解析
                if (available > 0) {
                    unavailableCount = 0;
                    ecgParser24.ecgParserPacket(tmp, tmp.length);
                } else {
                    unavailableCount++;
                }
                try {
                    // 二代机usb的板子每隔4毫秒取一次数据
                    if (usbVersion == 2) {
                        Thread.sleep(4);
                        //三代机的usb的板子每隔1毫秒取一次数据（实际板子是每2毫秒发一次数据）
                    } else if (usbVersion == 3) {
                        Thread.sleep(1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (unavailableCount > 300) {
                    isReceiveBTData = false;
                    Message msg = handler.obtainMessage(BT_CONNECT_DEVICE_ERROR);
                    msg.obj = "接收信号异常。\n" + "请确认USB连接是否出现松动，确认USB插紧后，重新开始测量。";
                    handler.sendMessage(msg);
                    break;
                }
            }
        } catch (IOException e) {
            if (!e.getMessage().equals("change_error")){
                e.printStackTrace();
                Message msg = handler.obtainMessage(BT_CONNECT_FAILED);
                msg.obj = "数据传输出现异常，请重新打开设备再次测量！" + e.getMessage();
                handler.sendMessage(msg);
            }

        }
    }


    /***
     * 停止串口的数据传输
     */
    public void stopSerial() {
        if (usPort != null&&isReceiveBTData) {
            try {
                ecgParser24.stopInit();
                usPort.write(ParseOriginEcgData.packEcgDeviceStop(), READ_WAIT_MILLIS);
                //先阻塞线程
                Thread.sleep(100);
                //调用interrupt()触发异常结束线程
                interrupt();
                isReceiveBTData = false;
            } catch (IOException | InterruptedException e) {
                usbDConn.close();
                usbDConn=null;
                try {
                    usPort.close();
                    usPort=null;
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }

            }
        }
    }

}
